package com.firebird.app.fejpsl.ui.activity

import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.fragment.app.FragmentTransaction
import com.firebird.app.fejpsl.R
import com.firebird.app.fejpsl.app.App
import com.firebird.app.fejpsl.base.BaseMvpActivity
import com.firebird.app.fejpsl.constant.Constant
import com.firebird.app.fejpsl.event.LoginEvent
import com.firebird.app.fejpsl.event.RefreshHomeEvent
import com.firebird.app.fejpsl.ext.showToast
import com.firebird.app.fejpsl.mvp.contract.MainContract
import com.firebird.app.fejpsl.mvp.model.bean.UserInfoBody
import com.firebird.app.fejpsl.mvp.presenter.MainPresenter
import com.firebird.app.fejpsl.ui.fragment.*
import com.firebird.app.fejpsl.utils.DialogUtil
import com.firebird.app.fejpsl.utils.Preference
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.toolbar.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread

class MainActivity : BaseMvpActivity<MainContract.View, MainContract.Presenter>(), MainContract.View {

    private val BOTTOM_INDEX:String="bottom_index"

    private val FRAGMENT_HOME=0X01
    private val FRAGMENT_CLASSROOM = 0x02
    private val FRAGMENT_SWORD = 0x03
    private val FRAGMENT_DISCOVER = 0x04
    private val FRAGMENT_ME = 0x05

    private var mIndex = FRAGMENT_HOME

    private var mHomeFragment: HomeFragment? = null
    private var mClassroomFragment: ClassroomFragment? = null
    private var mSwordFragment: SwordFragment? = null
    private var mDiscoverFragment: DiscoverFragment? = null
    private var mMeFragment: MeFragment? = null

    private var mExitTime: Long = 0

    /**
     * local username
     */
    private var username: String by Preference(Constant.USERNAME_KEY, "")

    /**
     * username TextView
     */
    private var nav_username: TextView? = null
    /**
     * user_id TextView
     */
    private var nav_user_id: TextView? = null
    /**
     * user_grade TextView
     */
    private var nav_user_grade: TextView? = null
    /**
     * user_rank TextView
     */
    private var nav_user_rank: TextView? = null
    /**
     * score TextView
     */
    private var nav_score: TextView? = null
    /**
     * rank ImageView
     */
    private var nav_rank: ImageView? = null

    override fun attachLayoutRes(): Int = R.layout.activity_main

    override fun createPresenter(): MainContract.Presenter = MainPresenter()

    override fun useEventBus(): Boolean = true

    override fun initData() {
       // Beta.checkUpgrade(false, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        if(savedInstanceState!=null){
            mIndex=savedInstanceState?.getInt(BOTTOM_INDEX)
        }
        super.onCreate(savedInstanceState)
    }

    override fun initView() {
        super.initView()
       /* toolbar.run {
            title = getString(R.string.app_name)
            setSupportActionBar(this)
        }*/

        bottom_navigation.run {
            // 以前使用 BottomNavigationViewHelper.disableShiftMode(this) 方法来设置底部图标和字体都显示并去掉点击动画
            // 升级到 28.0.0 之后，官方重构了 BottomNavigationView ，目前可以使用 labelVisibilityMode = 1 来替代
            // BottomNavigationViewHelper.disableShiftMode(this)
            labelVisibilityMode = 1
            setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
        }

        initDrawerLayout()
       // initNavView()

        showFragment(mIndex)

       // floating_action_btn.run {
       //     setOnClickListener(onFABClickListener)
       // }
    }

    override fun start() {
        // 获取用户个人信息
        mPresenter?.getUserInfo()
    }

    override fun initColor() {
        //super.initColor()
        //refreshColor(ColorEvent(true))
    }

    /**
     * init DrawerLayout
     */
    private fun initDrawerLayout() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            var params = window.attributes
//            params.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
//            drawer_layout.fitsSystemWindows = true
//            drawer_layout.clipToPadding = false
//        }
        drawer_layout.run {
            val toggle = ActionBarDrawerToggle(
                    this@MainActivity,
                    this,
                    toolbar
                    , R.string.navigation_drawer_open,
                    R.string.navigation_drawer_close)
            addDrawerListener(toggle)
            toggle.syncState()
        }
    }

    /**
     * 显示用户信息，包括积分、等级、排名
     */
    override fun showUserInfo(bean: UserInfoBody) {
        App.userInfo = bean

        nav_user_id?.text = bean.userId.toString()
        nav_user_grade?.text = (bean.coinCount / 100 + 1).toString()
        nav_user_rank?.text = bean.rank.toString()
        nav_score?.text = bean.coinCount.toString()
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshHomeEvent(event: RefreshHomeEvent) {
        if (event.isRefresh) {
            mHomeFragment?.lazyLoad()
        }
    }


    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState?.putInt(BOTTOM_INDEX, mIndex)
    }

    /**
     * 展示Fragment
     * @param index
     */
    private fun showFragment(index: Int) {
        val transaction = supportFragmentManager.beginTransaction()
        hideFragments(transaction)
        mIndex = index
        when (index) {
            FRAGMENT_HOME // 首页
            -> {
                //toolbar.title = getString(R.string.app_name)
                if (mHomeFragment == null) {
                    mHomeFragment = HomeFragment.getInstance()
                    transaction.add(R.id.container, mHomeFragment!!, "home")
                } else {
                    transaction.show(mHomeFragment!!)
                }
            }
            FRAGMENT_CLASSROOM  // 课堂
            -> {
               // toolbar.title = getString(R.string.classroom)
                if (mClassroomFragment == null) {
                    mClassroomFragment = ClassroomFragment.getInstance()
                    transaction.add(R.id.container, mClassroomFragment!!, "classroom")
                } else {
                    transaction.show(mClassroomFragment!!)
                }
            }
            FRAGMENT_SWORD // 论剑
            -> {
               // toolbar.title = getString(R.string.sword)
                if (mSwordFragment == null) {
                    mSwordFragment = SwordFragment.getInstance()
                    transaction.add(R.id.container, mSwordFragment!!, "sword")
                } else {
                    transaction.show(mSwordFragment!!)
                }
            }
            FRAGMENT_DISCOVER // 发现
            -> {
                //toolbar.title = getString(R.string.discover)
                if (mDiscoverFragment == null) {
                    mDiscoverFragment = DiscoverFragment.getInstance()
                    transaction.add(R.id.container, mDiscoverFragment!!, "discover")
                } else {
                    transaction.show(mDiscoverFragment!!)
                }
            }
            FRAGMENT_ME // 我
            -> {
                //toolbar.title = getString(R.string.me)
                if (mMeFragment == null) {
                    mMeFragment = MeFragment.getInstance()
                    transaction.add(R.id.container, mMeFragment!!, "me")
                } else {
                    transaction.show(mMeFragment!!)
                }
            }
        }
        transaction.commit()
    }

    /**
     * 隐藏所有的Fragment
     */
    private fun hideFragments(transaction: FragmentTransaction) {
        mHomeFragment?.let { transaction.hide(it) }
        mClassroomFragment?.let { transaction.hide(it) }
        mSwordFragment?.let { transaction.hide(it) }
        mDiscoverFragment?.let { transaction.hide(it) }
        mMeFragment?.let { transaction.hide(it) }
    }

    /**
     * NavigationItemSelect监听
     */
    private val onNavigationItemSelectedListener =
            BottomNavigationView.OnNavigationItemSelectedListener { item ->
                return@OnNavigationItemSelectedListener when (item.itemId) {
                    R.id.action_home -> {
                        showFragment(FRAGMENT_HOME)
                        true
                    }
                    R.id.action_classroom -> {
                        showFragment(FRAGMENT_CLASSROOM)
                        true
                    }
                    R.id.action_sword -> {
                        showFragment(FRAGMENT_SWORD)
                        true
                    }
                    R.id.action_discover -> {
                        showFragment(FRAGMENT_DISCOVER)
                        true
                    }
                    R.id.action_me -> {
                        showFragment(FRAGMENT_ME)
                        true
                    }
                    else -> {
                        false
                    }

                }
            }


    private fun goCommonActivity(type: String) {
        Intent(this@MainActivity, CommonActivity::class.java).run {
            putExtra(Constant.TYPE_KEY, type)
            startActivity(this)
        }
    }

    /**
     * 去登陆页面
     */
    private fun goLogin() {
        Intent(this@MainActivity, LoginActivity::class.java).run {
            startActivity(this)
        }
    }

    override fun recreate() {
        try {
            val fragmentTransaction = supportFragmentManager.beginTransaction()
            if (mHomeFragment != null) {
                fragmentTransaction.remove(mHomeFragment!!)
            }
            if (mClassroomFragment != null) {
                fragmentTransaction.remove(mClassroomFragment!!)
            }
            if (mSwordFragment != null) {
                fragmentTransaction.remove(mSwordFragment!!)
            }
            if (mDiscoverFragment != null) {
                fragmentTransaction.remove(mDiscoverFragment!!)
            }
            if (mMeFragment != null) {
                fragmentTransaction.remove(mMeFragment!!)
            }
            fragmentTransaction.commitAllowingStateLoss()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        super.recreate()
    }

    /**
     * 退出登录 Dialog
     */
    private val mDialog by lazy {
        DialogUtil.getWaitDialog(this@MainActivity, resources.getString(R.string.logout_ing))
    }

    /**
     * Logout
     */
    private fun logout() {
        DialogUtil.getConfirmDialog(this, resources.getString(R.string.confirm_logout),
                DialogInterface.OnClickListener { _, _ ->
                    mDialog.show()
                    mPresenter?.logout()
                }).show()
    }

    override fun showLogoutSuccess(success: Boolean) {
        if (success) {
            doAsync {
                // CookieManager().clearAllCookies()
                Preference.clearPreference()
                uiThread {
                    mDialog.dismiss()
                    showToast(resources.getString(R.string.logout_success))
                    username = nav_username?.text.toString().trim()
                    isLogin = false
                    EventBus.getDefault().post(LoginEvent(false))
                }
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        if (mIndex != FRAGMENT_CLASSROOM) {
            menuInflater.inflate(R.menu.menu_activity_main, menu)
        }
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.action_search -> {
                Intent(this, SearchActivity::class.java).run {
                    startActivity(this)
                }
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis().minus(mExitTime) <= 2000) {
                finish()
            } else {
                mExitTime = System.currentTimeMillis()
                showToast(getString(R.string.exit_tip))
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
        mHomeFragment = null
        mClassroomFragment = null
        mSwordFragment = null
        mDiscoverFragment = null
        mMeFragment = null
    }

}
